<template>
  <div class="app-container">
    <el-row :gutter="10" class="mb8" v-if="optType != 'view' && optType != 'finish' && optType != 'confirm' && status">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['pro:outsourcing:add']"
          >新增
        </el-button>
      </el-col>

    </el-row>

    <el-table border v-loading="loading" :data="outsourceWorkorderList" @selection-change="handleSelectionChange">
      <el-table-column label="外协工序编号" align="center" prop="workorderCode" width="140" :show-overflow-tooltip="true"/>
      <el-table-column label="外协工序" align="center" prop="processName" width="100" :show-overflow-tooltip="true"/>
      <el-table-column label="需求数量" align="center" prop="quantity" width="80" :show-overflow-tooltip="true"/>
      <el-table-column label="需求日期" align="center" prop="deadline" :show-overflow-tooltip="true"/>
      <el-table-column label="生产商" width="100" align="center" prop="manufactureName" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remark" :show-overflow-tooltip="true">
      </el-table-column>
      <el-table-column fixed="right" label="操作" align="center" v-if="optType != 'view' && optType != 'finish' && optType != 'confirm' && status">
        <template slot-scope="scope">
          <el-button
            style="line-height: 30px;"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['pro:outsourcing:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['pro:outsourcing:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改生产任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1080px" append-to-body>
      <el-form ref="form" :model="form" label-width="100px" :rules="rules">

        <el-row>
          <el-col :span="8">
            <el-form-item label="工单编号" prop="workorderCode">
              <el-input v-model="form.workorderCode" :readonly="actionType != 'save'"  placeholder="请输入工单编号"/>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <el-form-item label-width="80">
              <el-switch
                v-model="autoGenFlag"
                active-color="#13ce66"
                active-text="自动生成"
                @change="handleAutoGenChange(autoGenFlag)"
                v-if="actionType == 'save' "
              >
              </el-switch>
            </el-form-item>
          </el-col>

        </el-row>
        <el-row>

          <el-col :span="12">
            <el-form-item label="外协工序" prop="routeProcessId" >
              <el-select v-model="form.routeProcessId"  :disabled="actionType != 'save'"  placeholder="请选择外协工序" @change="getOutsourcedManufactureList">
                <el-option
                  v-for="item in processOptions"
                  :key="item.recordId"
                  :label="item.processName"
                  :value="item.recordId"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产商" prop="manufactureId" >
              <el-select v-model="form.manufactureId"  filterable  placeholder="请选择外协生产商" >
                <el-option
                  v-for="out in outsourcedManufactureList"
                  :key="out.manufactureId"
                  :label="out.manufactureName"
                  :value="out.manufactureId"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="工单数量" prop="quantity">
              <el-input-number :min="1" v-model="form.quantity" disabled placeholder="请输入生产数量"/>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="需求日期" prop="deadline">
              <el-date-picker
                clearable
                v-model="form.deadline"
                type="date"
                value-format="yyyy-MM-dd"
                placeholder="请选择需求日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>


        <el-row>
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="form.remark" type="textarea"  placeholder="请输入内容"/>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { addOutsourcing, delOutsourcing, getOutsourcing, updateOutsourcing } from "@/api/mes/pro/outsourcing";
import { getOutsourcedManufacture, getOutsourceWorkorder } from "@/api/mes/pro/workticket";
import { listProcess } from '@/api/mes/pro/routeprocess';
import { genCode } from "@/api/system/autocode/rule";

export default {
  name: 'outsourcePlan',

  data() {
    return {
      actionType: 'save',
      autoGenFlag:false,
      processOptions:[],
      status: true,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 生产任务表格数据
      outsourceWorkorderList: [],
      outsourcedManufactureList:[],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderCode: this.workorderCode,
      },
      // 表单参数
      form: {
        workorderCode:null,
        workorderName:null,
        routeProcessId:null,
        routeId:null,
        processId:null,
        quantity:this.quantity,
        remark:null,
        deadline:this.requestDate,
      },
      // 表单校验
      rules: {
        workorderCode: [{ required: true, message: '编号不能为空', trigger: 'blur' }],
        quantity: [{ required: true, message: '需求数量不能为空', trigger: 'blur' }],
        deadline: [{ required: true, message: '需求日期不能为空', trigger: 'blur' }],
        routeProcessId: [{ required: true, message: '外协工序不能为空', trigger: 'blur' }],
        manufactureId: [{ required: true, message: '外协生产商不能为空', trigger: 'blur' }],
      }
    };
  },
  props: {
    workorderCode: null,
    quantity: null,
    optType: null,
    routeId:null,
    requestDate:null,
  },


  watch: {
    workorderCode: {
      handler(newValue, oldValue) {
        this.queryParams.orderCode=newValue;
        this.getList();

      },
      deep: true
    }
  },

  created() {
    this.getList();
  },
  methods: {
    //自动生成编号
    handleAutoGenChange(autoGenFlag) {
      if (autoGenFlag) {
        genCode('WORKORDER_CODE').then(response => {
          this.form.workorderCode = response;
        });
      } else {
        this.form.workorderCode = null;
      }
    },
    //获取当前产品对应的所有外协生产工序
    getProcess() {
      listProcess(this.routeId,'Y').then(response => {
        this.processOptions = response.data;
        if(this.processOptions&&this.processOptions.length>0){
          if(!this.form.routeProcessId) {
            this.form.routeProcessId = this.processOptions[0].recordId
            this.form.processId=this.processOptions[0].processId
            this.form.processName=this.processOptions[0].processName
            getOutsourcedManufacture(this.processOptions[0].outManufacture).then(response => {
              this.outsourcedManufactureList=response.data;
              if(this.outsourcedManufactureList&&this.outsourcedManufactureList.length>0&&!this.form.manufactureId) {
                this.form.manufactureId = this.outsourcedManufactureList[0].manufactureId
              }
            });
          }else{
            getOutsourcedManufacture(this.processOptions.find(item=>{
              if( item.recordId==this.form.routeProcessId){
                this.form.processId=item.processId
                this.form.processName= item.processName
                return true;
              }
            }).outManufacture).then(response => {
              this.outsourcedManufactureList=response.data;
            })
          }
        }
      });
    },
    //某个工序下的外协生产商
    getOutsourcedManufactureList(){
     let item= this.processOptions.find(item=>{
        if( item.recordId==this.form.routeProcessId){
          this.form.processId=item.processId
          this.form.processName= item.processName
          this.form.routeId=item.routeId
          return true;
        }
      })
      getOutsourcedManufacture(item.outManufacture).then(response => {
        this.outsourcedManufactureList=response.data;
        if(this.outsourcedManufactureList&&this.outsourcedManufactureList.length>0&&!this.form.manufactureId) {
          this.form.manufactureId = this.outsourcedManufactureList[0].manufactureId
        }
      });
    },
    /** 查询生产任务列表 */
    getList() {
      this.loading = true;
        getOutsourceWorkorder(this.queryParams).then(response => {
          this.outsourceWorkorderList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.autoGenFlag=false;
      this.form = {
        workorderCode:null,
        workorderName:null,
        routeProcessId:null,
        processId:null,
        routeId:null,
        processName:null,
        manufactureId:null,
        quantity:this.quantity,
        remark:null,
        deadline:this.requestDate,
      };
      this.resetForm('form');
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm');
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.taskId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.form.quantity = this.quantity;
      this.open = true;
      this.title = '添加外协工单';
      this.getProcess();
      this.actionType='save'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();

      getOutsourcing(row.workorderId).then(response => {
        this.form = response.data;
        // this.form.startTime = new Date(response.data.startTime);
        // this.form.endTime = new Date(response.data.endTime);
        this.open = true;
        this.getProcess();
        this.title = '修改外协工单';
        this.actionType='update'
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate(valid => {
        if (valid) {
          this.form.orderCode=this.workorderCode;
          if (this.form.workorderId != null) {

            updateOutsourcing({workorderId:this.form.workorderId,
              workorderName:this.form.workorderName,
              manufactureId:this.form.manufactureId,
              remark:this.form.remark,
              deadline:this.form.deadline}).then(response => {
              this.$modal.msgSuccess('修改成功');
              this.open = false;
              this.getList();
            });
          } else {
            addOutsourcing(this.form).then(response => {
              this.$modal.msgSuccess('新增成功');
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$modal
        .confirm('是否确认删除外协工单编号为"' + row.workorderCode + '"的数据项？')
        .then(function () {
          return delOutsourcing(row.workorderId);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess('删除成功');
        })
        .catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download(
        'mes/pro/protask/export',
        {
          ...this.queryParams
        },
        `protask_${new Date().getTime()}.xlsx`
      );
    },
    handleWorkstationSelect() {
      this.$refs.wsSelect.showFlag = true;
    },
    onWorkstationSelected(row) {
      if (row != undefined && row != null) {
        this.form.workstationId = row.workstationId;
        this.form.workstationCode = row.workstationCode;
        this.form.workstationName = row.workstationName;
        this.form.attr2 = row.workshopName;
        this.form.attr4 = row.workshopId;
      }
    },
    //点击人员选择按钮
    handleUserSelect() {
      this.$refs.userSelect.showFlag = true;
    },
    //人员选择返回
    onUserSelected(row) {
      if (row != undefined && row != null) {
        this.form.attr1 = row.map(item => item.nickName).join(',');
        this.form.attr3 = row.map(item => item.userId).join(',');
      }
    }
  }
};
</script>
